package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrReponseVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();

        BeanUtils.copyProperties(attr,attrEntity);

        this.save(attrEntity);

        if (attr.getAttrType() == 1){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();

            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());

            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());

            relationDao.insert(attrAttrgroupRelationEntity);
        }


    }

    @Override
    public PageUtils queryBaseAttyPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type","base".equalsIgnoreCase(attrType)?1:0);

        if (catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper) ->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();

        List<AttrReponseVo> vos = records.stream().map((attrEntity) -> {
            AttrReponseVo attrReponseVo = new AttrReponseVo();
            BeanUtils.copyProperties(attrEntity,attrReponseVo);

            if ("base".equalsIgnoreCase(attrType)){
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));

                if (relationEntity != null){
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrReponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }


            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null){
                attrReponseVo.setCatelogName(categoryEntity.getName());
            }

            return attrReponseVo;

        }).collect(Collectors.toList());


        pageUtils.setList(vos);
        return pageUtils;


    }

    @Override
    public AttrReponseVo getAttrInfo(Long attrId) {
        AttrReponseVo reponseVo = new AttrReponseVo();

        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,reponseVo);

        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_id", attrEntity.getAttrId()));

        if (relationEntity != null){
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            reponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
            reponseVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
        }

        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());

        if (categoryEntity != null){
            reponseVo.setCatelogName(categoryEntity.getName());
            Long[] catelogPath = categoryService.findCatelogPath(categoryEntity.getCatId());
            reponseVo.setCatelogPath(catelogPath);
        }

        return reponseVo;

    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);

        this.updateById(attrEntity);

        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());

        relationDao.update(attrAttrgroupRelationEntity
                ,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));

    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId));

        List<Long> attrIds = new ArrayList<>();

        for(AttrAttrgroupRelationEntity entity : relationEntities){
            attrIds.add(entity.getAttrId());
        }

        Collection<AttrEntity> attrEntities;

        if (attrIds.size() > 0){
            attrEntities = this.listByIds(attrIds);
        }else {
            attrEntities = null;
        }

        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrGroupRelationVo> attrGroupRelationVos = Arrays.asList(vos);

        List<AttrAttrgroupRelationEntity> relationEntities = new ArrayList<>();

        for (AttrGroupRelationVo vo : attrGroupRelationVos) {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo,entity);
            relationEntities.add(entity);
        }

        relationDao.deleteBach(relationEntities);
    }

    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {

        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        CategoryEntity categoryEntity = categoryDao.selectById(attrGroupEntity.getCatelogId());
        //分类下的所有属性


        //2、当前分组只能关联别的分组没有引用的属性

        //2.1)、当前分类下的其他分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().
                ne("attr_group_id", attrgroupId).
                eq("catelog_id", categoryEntity.getCatId()));
        List<Long> groupIds = new ArrayList<>();
        for(AttrGroupEntity entity : attrGroupEntities){
            groupIds.add(entity.getAttrGroupId());
        }
        //2.2)、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().
                in("attr_group_id", groupIds));
        List<Long> attrIds = new ArrayList<>();
        for (AttrAttrgroupRelationEntity reEn: relationEntities) {
            attrIds.add(reEn.getAttrId());
        }

        //2.3)、从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>().
                eq("catelog_id", categoryEntity.getCatId());

        if (attrIds != null && attrIds.size() != 0){
            attrEntityQueryWrapper.notIn("attr_id",attrIds);
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);

        return new PageUtils(page);
    }

}